<?php
// 定义TOKEN
define("TOKEN", "dataoffice");
//---------------------------------------------------------------------//实例化类,判断是否已验证token
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr']))
	{
		$wechatObj->responseMsg();
	}
else
	{
		$wechatObj->valid();
	}
//---------------------------------------------------------------------//定义类
class wechatCallbackapiTest
{
//---------------------------------------------------------------------
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature())
			{
				echo $echoStr;
				exit;
			}
    }
//---------------------------------------------------------------------//验证服务器
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature)
			{
				return true;
			}
		else
			{
				return false;
			}
    }
//---------------------------------------------------------------------//消息类型判断
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr))
			{
				$this->logger("R".$postStr);
				$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
				$RX_TYPE = trim($postObj->MsgType);
				switch ($RX_TYPE)
					{
						case "event":
							$result = $this->receiveEvent($postObj);
							break;
						case "text":
							$result = $this->receiveText($postObj);
							break;
						case "image":
							$result = $this->receiveImage($postObj);
							break;
						case "voice":
							$result = $this->receiveVoice($postObj);
							break;
						case "link":
							$result = $this->receiveLink($postObj);
							break;
						case "location":
							$result = $this->receiveLocation($postObj);
							break;
						case "video":
							$result = $this->receiveVideo($postObj);
							break;
						default:
							$result = "unknow msg type: ".$RX_TYPE;
					}
				echo $result;
			}
		else
			{
			echo "";
			exit;
			}
    } 
//---------------------------------------------------------------------//接收事件消息
    private function receiveEvent($object) 
    {
        $content = "";
        switch ($object->Event)
			{
				case "subscribe":
					$content = "欢迎关注数据工作室\n输入地点查询今日天气";
					break;
				case "unsubscribe":
					$content = "取消关注";
					break;
				case "CLICK":
					$content = "取消关注";
					break;
				case "VIEW":
					$content = "取消关注";
					break;
				case "scancode_push":
					$content = "取消关注";
					break;
				case "scancode_waitmsg":
					$content = "取消关注";
					break;
				case "pic_sysphoto":
					$content = "取消关注";
					break;
				case "pic_photo_or_album":
					$content = "取消关注";
					break;
				case "pic_photo_or_album":
					$content = "取消关注";
					break;
				case "pic_photo_or_album":
					$content = "取消关注";
					break;
				case "pic_photo_or_album":
					$content = "取消关注";
					break;
			}
        //调用XML封装函数
        $result = $this->transmitText($object, $content);  
        return $result;
    }
//---------------------------------------------------------------------//接收文本消息  
    private function receiveText($object)  
    {
        $keyword = trim($object->Content);
        if($keyword == "时间")
			{
				$content = date('Y-m-d H:i:s',time());
				//调用XML封装函数
				$result = $this->transmitText($object, $content);   
            }
			//回复天气
		elseif(strstr($keyword, "天气"))
			{
				$city = str_replace('天气', '', $keyword);
				if($city == "")
				{
					$content = "请输入城市+天气，例如广州天气";
					$result = $this->transmitText($object, $content);
				}
				else
				{
					include("weather.php");
					$content = getWeatherInfo($city);
					$result = $this->transmitNews($object, $content);
				}
				return $result;
			}
		//回复单图文消息
        elseif($keyword == "图文" || $keyword == "单图文")    
			{
				$content = array();
				$content[] = array("Title"=>"单图文标题", 
									"Description"=>"单图文内容", 
									"PicUrl"=>"http://www.dataoffice.cn/weixin/weather/icon/day/01.png", 
									"Url" =>"http://www.dataoffice.cn");
				$result = $this->transmitNews($object, $content);
			}
		//回复多图文消息
        elseif($keyword == "多图文")            
			{
				$content = array();
				$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://www.dataoffice.cn/weixin/icon/cartoon.png", "Url" =>"http://www.dataoffice.cn");
				$content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://www.dataoffice.cn/weixin/weather/icon/day/01.png", "Url" =>"http://www.dataoffice.cn");
				$content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://www.dataoffice.cn/weixin/weather/icon/day/01.png", "Url" =>"http://www.dataoffice.cn");
				$result = $this->transmitNews($object, $content);
           
			}
	    //回复音乐消息
        elseif($keyword == "音乐")           
			{
				$content = array("Title"=>"Fade", 
				"Description"=>"歌手：Alan Walker", 
				"MusicUrl"=>"http://www.dataoffice.cn/weixin/AlanWalkerFade.mp3",
				"HQMusicUrl"=>"http://www.dataoffice.cn/weixin/AlanWalkerFade.mp3");
				$result = $this->transmitMusic($object, $content);
			}
		else
			{
				$content = "“".$keyword."”"."不是关键词，请重新输入";
				//调用XML封装函数
				$result = $this->transmitText($object, $content);   
            }
        return $result;
    }
//---------------------------------------------------------------------//接收图文消息
    private function receiveImage($object)  
    {
			$content = array("MediaId"=>$object->MediaId);
			//调用XML封装函数
			$result = $this->transmitImage($object, $content);   
			return $result;
	}
//---------------------------------------------------------------------//接收语音消息
	private function receiveVoice($object)  
    {
			$content = array("MediaId"=>$object->MediaId);
			//调用XML封装函数
			$result = $this->transmitVoice($object, $content);   
			return $result;
	}
//---------------------------------------------------------------------//接收链接消息
	private function receiveLink($object)  
    {
			$content = "你发送的是链接";
			//调用XML封装函数
			$result = $this->transmitText($object, $content);   
			return $result;
    }
//---------------------------------------------------------------------//接收位置消息
	private function receiveLocation($object)  
    {
			$content = "你发送的是位置";
			//调用XML封装函数
			$result = $this->transmitText($object, $content);   
			return $result;
	}
//---------------------------------------------------------------------//接收视频消息
	private function receiveVideo($object)  
    {
			$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
			//调用XML封装函数
			$result = $this->transmitVideo($object, $content);   
			return $result;
	}
//---------------------------------------------------------------------//XML文本封装函数
    private function transmitText($object, $content)   
    {
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
//---------------------------------------------------------------------//XML图片封装函数
    private function transmitImage($object, $imageArray)   
    {
		$itemTp1 = "<Image>
					<MediaId><![CDATA[%s]]></MediaId>
					</Image>";
		$item_str = sprintf($itemTp1,$imageArray['MediaId']);
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[image]]></MsgType>
					$item_str
					</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
//---------------------------------------------------------------------//XML语音封装函数
    private function transmitVoice($object, $voiceArray)   
    {
		$itemTp1 = "<Vioce>
					<MediaId><![CDATA[%s]]></MediaId>
					</Vioce>";
		$item_str = sprintf($itemTp1,$vioceArray['MediaId']);
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[voice]]></MsgType>
					$item_str
					</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
//---------------------------------------------------------------------//XML视频封装函数
    private function transmitVideo($object, $videoArray)   
    {
		$itemTpl = "<Video>
					<MediaId><![CDATA[%s]]></MediaId>
					<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
					<Title><![CDATA[%s]]></Title>
					<Description><![CDATA[%s]]></Description>
					</Video>";
        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[video]]></MsgType>
					$item_str
					</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
//---------------------------------------------------------------------//XML音乐封装函数 
    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<MusicUrl><![CDATA[%s]]></MusicUrl>
		<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
		</Music>";
        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
        $textTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[music]]></MsgType>
		$item_str
		</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
//---------------------------------------------------------------------//XML图文封装函数
    private function transmitNews($object, $arr_item)   
    {
        if(!is_array($arr_item))
            return;
        $itemTpl = "<item>
					<Title><![CDATA[%s]]></Title>
					<Description><![CDATA[%s]]></Description>
					<PicUrl><![CDATA[%s]]></PicUrl>
					<Url><![CDATA[%s]]></Url>
					</item>";           
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<Content><![CDATA[]]></Content>
					<ArticleCount>%s</ArticleCount>
					<Articles>
					$item_str
					</Articles>
					</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
        return $result;
    }
//---------------------------------------------------------------------
	private function logger($content)        //日志记录函数
	{
	}
}
?>